package com.intexh.quickandroid.module.chat.ChatManager;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import java.io.File;
import java.util.UUID;

public enum VoiceManager {
    /* 录制的音频文件 */
	INSTANCE;

    long start = 0;
    long end = 0;
    private File mRecAudioFile;
    /* MediaRecorder对象 */
    private MediaRecorder mMediaRecorder;
    private MediaPlayer mediaPlayer;
    private IPlayListener iPlayListener;
    private IRecoderListener iRecoderListener ;
    private int BASE = 600;
    private int SPACE = 300;// 间隔取样时间
    public static final int START= 0 ;
    public static final int RECODING = 1 ;
    public static final int SENDRECOING= 2 ;
    public static final int CANCELRECOD= 3 ;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==START){
                if(iRecoderListener!=null){
                    iRecoderListener.recording(0);
                }
            }else if(msg.what==SENDRECOING){
                if(iRecoderListener!=null){
                    iRecoderListener.stopedRecorder(mMediaRecorder, mRecAudioFile.getAbsoluteFile(),end-start);
                }
            }else  if(msg.what==CANCELRECOD){
               if(iRecoderListener!=null){
                   iRecoderListener.cancelRecorder();
               }
            }
        }
    } ;
    public interface IPlayListener {
        public void startPlay(MediaPlayer mediaPlayer);

        public void stopPlay(MediaPlayer mediaPlayer);
        
        public void onPlayError();
    }
    public interface IRecoderListener {
        public void startRecorder(MediaRecorder recorder);

        public void recording(int db) ;

        public void stopedRecorder(MediaRecorder mr, File file, long length);

        public void cancelRecorder() ;
    }
    /**
     * Called when the activity is first created.
     */
    private VoiceManager() {
    }

    private void setiPlayListener(IPlayListener iPlayListener) {
        this.iPlayListener = iPlayListener;
    }

    public void setiRecoderListener(IRecoderListener iRecoderListener) {
        this.iRecoderListener = iRecoderListener;
    }

    private Runnable mUpdateMicStatusTimer = new Runnable() {
        public void run() {
            updateRecoding();
        }
    };

    private void updateRecoding(){
        if (mMediaRecorder != null) {
            int ratio = mMediaRecorder.getMaxAmplitude() / BASE;
            int db = 0;// 分贝
            if (ratio > 1)
                db = (int) (20 * Math.log10(ratio));
            mHandler.postDelayed(mUpdateMicStatusTimer, SPACE);
            sendMessage(START,null);
        }

    }

    private void sendMessage(int wath,Object o){
        Message message = new Message() ;
        message.what = wath ;
        message.obj = o ;
        mHandler.sendMessage(message) ;
    }


    public void record(final Context mContext) {
        start = System.currentTimeMillis();
        new Thread(){
            @Override
            public void run() {
                synchronized (this) {
                    try {
                    	//录音时停止播放
                    	stopPlay();
                    	
                        if(iRecoderListener!=null){
                            iRecoderListener.startRecorder(mMediaRecorder);
                        }
                        File dir = new File(getCachDir(mContext));
                        dir.mkdirs();
            /* 创建录音文件 */
                        mRecAudioFile = new File(dir.getAbsolutePath() + File.separator
                                + UUID.randomUUID().toString() + ".amr");
                        mRecAudioFile.createNewFile();
                        if (mMediaRecorder != null) {
                            mMediaRecorder.reset();
                        }
            /* 实例化MediaRecorder对象 */
                        mMediaRecorder = new MediaRecorder();
			/* 设置麦克风 */
                        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
			/* 设置输出文件的格式 */
                        mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
			/* 设置音频文件的编码 */
                        mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
			/* 设置输出文件的路径 */
                        mMediaRecorder.setOutputFile(mRecAudioFile.getAbsolutePath());
                        mMediaRecorder.setMaxDuration(90000);
			/* 准备 */
                        mMediaRecorder.prepare();
			/* 开始 */
                        mMediaRecorder.start();
                        updateRecoding();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

    public void sendRecord() {
        end = System.currentTimeMillis();
        new Thread(){
            @Override
            public void run() {
                if (mRecAudioFile != null && mMediaRecorder != null) {
                    mMediaRecorder.reset();
                    mMediaRecorder = null;
                    sendMessage(SENDRECOING,null);
                }
            }
        }.start();
    }

    public void cancelRecord() {
        new Thread(){
            @Override
            public void run() {
                if (mRecAudioFile != null && mMediaRecorder != null) {
                    mMediaRecorder.reset();
                    mMediaRecorder = null;
                    sendMessage(CANCELRECOD,null);
                    mRecAudioFile.delete() ;
                }
            }
        }.start();
    }
    /* 播放录音文件 */
    public void playVoice(File file, IPlayListener iPlayListener) {
    	if (mediaPlayer == null) {
			mediaPlayer = new MediaPlayer();
		}
    	stopPlay();
    	setiPlayListener(iPlayListener);
        try {
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setDataSource(file.getAbsolutePath());
            mediaPlayer.setOnPreparedListener(onPreparedListener);
            mediaPlayer.setOnCompletionListener(onCompletionListener);
            mediaPlayer.prepare();
            mediaPlayer.setLooping(false);
            mediaPlayer.setVolume(1.0f,1.0f);
            mediaPlayer.start();
            iPlayListener.startPlay(mediaPlayer);
        } catch (Exception e) {
        	if(file != null)
        		file.delete();
        	if(iPlayListener != null)
        		iPlayListener.onPlayError();
            e.printStackTrace();
        }
    }


    private String getCachDir(Context mContext) {
        StringBuilder sb = new StringBuilder();
        String sdcardpath = Environment.getExternalStorageDirectory().getPath();
        if (sdcardpath != null) {
        	/* 2014-12-3上午10:54:54 Begin edited by YuSuCheng */
            return sb.append(sdcardpath).append(File.separator).append("zingchat")
                    .append(File.separator).append("voice").toString();
        } else {
            return sb.append(mContext.getCacheDir().getPath())
                    .append(File.separator).append("zingchat")
                    .append(File.separator).append("voice").toString();
        }
        /* 2014-12-3上午10:55:00 End edited by Yusucheng */
    }

    public void stopPlay() {
    	if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.reset();
		}
        if (iPlayListener != null) {
            iPlayListener.stopPlay(mediaPlayer);
		}
    }


    private OnPreparedListener onPreparedListener = new OnPreparedListener() {

        @Override
        public void onPrepared(MediaPlayer mp) {
        }
    };

    private OnCompletionListener onCompletionListener = new OnCompletionListener() {

        @Override
        public void onCompletion(MediaPlayer mp) {
            mediaPlayer.stop();
            mediaPlayer.reset();
           iPlayListener.stopPlay(mediaPlayer);
        }
    };

}

